package com.lovi.admin.controller;

import com.lovi.admin.param.AdminUserParam;
import com.lovi.admin.pojo.AdminUser;
import com.lovi.admin.service.AdminUserService;
import com.lovi.admin.utils.CustomAuthenticationToken;
import com.lovi.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;

/**
 *  后台管理用户处理controller
 */
@RestController
@Slf4j
public class AdminUserController {

    @Autowired
    private AdminUserService adminUserService;

    @PostMapping("/user/login")
    public R login(@Validated AdminUserParam adminUserParam, BindingResult result, HttpSession session){
        if (result.hasErrors()){
            return R.fail("核心参数为null,登录失败!");
        }

        //验证码校验
        String captcha = (String) session.getAttribute("captcha");

        if (!adminUserParam.getVerCode().equalsIgnoreCase(captcha)){
            return R.fail("验证码错误!");
        }
        AdminUser user =  adminUserService.login(adminUserParam);

        if (user == null){
            return R.fail("登录失败!账号或者密码错误!");
        }
        //管理端用户登录session
        session.setAttribute("userInfo",user);

        //获取用户 subject
        Subject subject = SecurityUtils.getSubject();
        //自定义的token封装类
        CustomAuthenticationToken token = new CustomAuthenticationToken(user);
        subject.login(token);

        return R.ok("登录成功!");
    }

    @GetMapping("user/logout")
    public R logout(HttpSession session){
        //移除登录信息session
        session.removeAttribute("userInfo");

        return R.ok("退出登录成功!");
    }

    /**
     * 查询用户的权限
     */
    @GetMapping("user/role")
    public R getRole(HttpSession session){
        AdminUser userInfo = (AdminUser) session.getAttribute("userInfo");
        log.info("AdminUserController.getRole 结果为->{}", userInfo.getUserRole());

        return R.ok("测试看看");
    }
    @RequestMapping("/noauth")
    @ResponseBody
    public String noAuth(){
        return "未经授权不能访问此页面";
    }

}
